<script lang="ts" setup>
import { RouteMap, useRouter } from '@/router';
import { useUserStore } from '@/store/user';
import { SEX_LIST } from '@/constants/sex';
import * as UserService from '../../api/user';
import { useAuthStore } from '@/store/auth';
import { GET_BASE_CONFIG } from '@/http/env';
import { decryptData } from '@/http/security';
import { onMounted, ref } from 'vue';
import { useLocale } from '@/locale/locale';
import { isWechat } from '@/utils/platform';

const { t } = useLocale();
const statusBarH = ref(0);
const router = useRouter();
const userStore = useUserStore();
const authStore = useAuthStore();

async function setBirthday(value: any) {
  const res = await UserService.setUserInfo({
    birthday: value.detail.value
  });
  if (res.code !== 0) {
    return uni.showToast({
      title: res.message,
      icon: 'none'
    });
  }
  userStore.setBirthday(value.detail.value);
}

async function setSex(value: any) {
  const res = await UserService.setUserInfo({
    sex: parseInt(value.detail.value) + 1
  });
  if (res.code == 0) {
    userStore.setSex(parseInt(value.detail.value) + 1);
  } else {
    return uni.showToast({
      title: res.message,
      icon: 'none'
    });
  }
}

async function logout() {
  await authStore.logout();
  userStore.setAvatar({
    detail: {
      avatarUrl: '/static/icon_not_logged_in.png'
    }
  });
  await uni.navigateBack();
}

function updateAvatar(filePath: string) {
  uni.showLoading({ title: 'Uploading...' });
  uni.uploadFile({
    url: GET_BASE_CONFIG().BASE_URL + '/api/upload/file', //仅为示例，非真实的接口地址
    filePath: filePath,
    name: 'file',
    header: {
      Uploadtype: 'image'
    },
    success: async (uploadFileRes) => {
      const uploadFileResData = JSON.parse(uploadFileRes.data);

      if (uploadFileResData.resCode != 0) {
        return uni.showToast({
          title: uploadFileResData.resMessage,
          icon: 'none'
        });
      }

      const resJsonData = decryptData(uploadFileResData.resData);

      if (resJsonData.code != 0) {
        return uni.showToast({
          title: resJsonData.message,
          icon: 'none'
        });
      }

      const response = await UserService.setUserInfo({
        avatar: resJsonData.data.fileUrl
      });

      if (response.code !== 0) {
        return uni.showToast({
          title: response.message,
          icon: 'none'
        });
      }

      userStore.setAvatar({
        detail: {
          avatarUrl: resJsonData.data.fileUrl
        }
      });
      closeCropperPopup();
    }
  });
}

async function chooseAvatar() {
  uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      imageSrc.value = res.tempFilePaths[0];
      openCropperPopup();
    }
  });
}

onMounted(() => {
  uni.getSystemInfo({
    success: (res) => {
      statusBarH.value = res.statusBarHeight || 0;
    }
  });
});

const cropperRef = ref();
const visible = ref(false);
const imageSrc = ref('');

function openCropperPopup() {
  visible.value = true;
}

function closeCropperPopup() {
  visible.value = false;
}

function handleCrop() {
  cropperRef.value.crop().then((res: string) => {
    updateAvatar(res);
  });
}
</script>

<template>
  <uni-nav-bar
    v-if="isWechat()"
    :border="false"
    :title="t('LUKey_userSetting')"
    fixed
    left-icon="left"
    status-bar
    @click-left="router.back"
  />

  <view :style="{ minHeight: 'calc(100vh - 44px - ' + statusBarH + 'px)' }" class="account-contain">
    <view class="account-contain-head" @click="chooseAvatar">
      <image :src="userStore.user.avatar" class="account-contain-head-img" />
      <view class="account-contain-head-camera">
        <image src="/static/icon_account_camera.png" />
      </view>
    </view>
    <view class="account-contain-input">
      <view class="account-contain-input-item">
        <text>{{ t('LUKey_nickname') }}</text>
        <view
          class="account-contain-input-item-view"
          @click="router.to(RouteMap.accountSet, { type: 'name' })"
        >
          <view :class="!userStore.user.fullName ? 'placeholder' : ''">
            {{ userStore.user.fullName ? userStore.user.fullName : t('LCKey_incomplete') }}
          </view>
          <image src="/static/icon_account_arrow_right.png" />
        </view>
      </view>
      <view class="account-contain-input-item">
        <text>{{ t('LUKey_email') }}</text>
        <view
          class="account-contain-input-item-view"
          @click="router.to(RouteMap.accountSet, { type: 'email' })"
        >
          <view :class="!userStore.user.email ? 'placeholder' : ''">
            {{ userStore.user.email ? userStore.user.email : t('LCKey_incomplete') }}
          </view>
          <image src="/static/icon_account_arrow_right.png" />
        </view>
      </view>
      <view class="account-contain-input-item">
        <text>{{ t('LUKey_mobile') }}</text>
        <view
          class="account-contain-input-item-view"
          @click="router.to(RouteMap.accountSet, { type: 'phone' })"
        >
          <view :class="!userStore.user.phoneNumber ? 'placeholder' : ''">
            {{ userStore.user.phoneNumber ? userStore.user.phoneNumber : t('LCKey_incomplete') }}
          </view>
          <image src="/static/icon_account_arrow_right.png" />
        </view>
      </view>
      <view class="account-contain-input-item">
        <text>{{ t('LCKey_birthday') }}</text>
        <view class="account-contain-input-item-view">
          <picker
            :value="userStore.user.birthday ? userStore.user.birthday : 0"
            mode="date"
            @change="setBirthday"
          >
            <view style="display: flex; align-items: center; justify-content: flex-end">
              <view v-if="!userStore.user.birthday" class="placeholder">
                {{ t('LCKey_incomplete') }}
              </view>
              <view v-else>
                {{ userStore.user.birthday }}
              </view>
              <image src="/static/icon_account_arrow_right.png" />
            </view>
          </picker>
        </view>
      </view>
      <view class="account-contain-input-item">
        <text>{{ t('LCKey_gender') }}</text>
        <view class="account-contain-input-item-view">
          <picker
            :range="SEX_LIST"
            :value="userStore.user.sex - 1"
            range-key="label"
            @change="setSex"
          >
            <view style="display: flex; align-items: center; justify-content: flex-end">
              <view v-if="!userStore.user.sex" class="placeholder">
                {{ t('LCKey_incomplete') }}
              </view>
              <view v-else>
                {{ SEX_LIST[userStore.user.sex - 1].label }}
              </view>
              <image src="/static/icon_account_arrow_right.png" />
            </view>
          </picker>
        </view>
      </view>
    </view>
    <view class="account-contain-btn logout" @click="logout">{{ t('LUKey_logout') }}</view>
    <view class="account-contain-btn remove" @click="router.to(RouteMap.userCancel)">
      {{ t('LRMKey_remoteAccount') }}
    </view>
  </view>

  <view v-show="visible" class="fixed top-0 left-0 z-50 w-screen h-screen bg-white">
    <bt-cropper ref="cropperRef" :imageSrc="imageSrc" :ratio="1" />
    <view class="absolute left-0 bottom-0 right-0 p-4">
      <button class="bg-green rounded border border-green" @click="handleCrop">
        <text class="text-base text-white">Crop</text>
      </button>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.account {
  &-contain {
    background: #ffffff;
    padding-bottom: 50rpx;
    padding-bottom: calc(constant(safe-area-inset-bottom) + 50rpx);
    padding-bottom: calc(env(safe-area-inset-bottom) + 50rpx);
    padding-top: 76rpx;
    width: 100%;

    &-head {
      height: 180rpx;
      margin: 0 auto 80rpx;
      position: relative;
      width: 180rpx;

      &-img {
        border-radius: 100%;
        height: 100%;
        width: 100%;
      }

      &-camera {
        background: #ffffff;
        border-radius: 100%;
        bottom: 0;
        height: 56rpx;
        padding: 8rpx;
        position: absolute;
        right: 0;
        width: 56rpx;

        image {
          display: block;
          height: 100%;
          width: 100%;
        }
      }
    }

    &-input {
      margin-bottom: 100rpx;

      &-item {
        align-items: center;
        display: flex;
        justify-content: space-between;
        padding-left: 32rpx;
        padding-right: 36rpx;

        text {
          color: #979797;
          font-size: 28rpx;
          font-weight: 400;
          line-height: 120rpx;
        }

        &-view {
          align-items: center;
          display: flex;
          flex: 1;
          height: 120rpx;
          justify-content: flex-end;

          picker {
            width: 100%;
          }

          view {
            color: #3d3d3d;
            flex: 1;
            font-size: 28rpx;
            font-weight: 400;
            text-align: right;

            &.placeholder {
              color: #979797;
            }
          }

          image {
            display: block;
            height: 20rpx;
            margin-left: 20rpx;
            width: 20rpx;
          }
        }
      }
    }

    &-btn {
      border-radius: 100rpx;
      color: #3d3d3d;
      font-size: 32rpx;
      font-weight: 500;
      height: 100rpx;
      line-height: 100rpx;
      margin: 0 auto 20rpx;
      text-align: center;
      width: 686rpx;

      &.logout {
        background: rgba(216, 216, 216, 0.549);
      }

      &.remove {
        background: rgba(255, 255, 255, 0.549);
        border: 2rpx solid #eaeaea;
      }
    }
  }
}
</style>
